package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.tanhua.sso.service.SmsService.CHECK_CODE;

@Service
@Slf4j
public class UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    /**
     * 用户登录
     *
     * @param phone 手机号
     * @param code  验证码
     * @return
     */
    public Map login(String phone, String code) {
        //验证码是否匹配
        String redisKey = CHECK_CODE + phone;
        boolean isNew = false;

        //校验验证码
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        if (!StringUtils.equals(code, redisData)) {
            return null; //验证码错误
        }

        //校验成功，将验证码删除
        this.redisTemplate.delete(redisKey);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getMobile, phone);
        //手机号是否存在
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            //给新用户注册
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));

            //注册新用户
            this.userMapper.insert(user);
            isNew = true;
        }

        //返回token
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        String token = Jwts.builder().setClaims(map)
                .signWith(SignatureAlgorithm.HS256, secret)
                .setExpiration(new DateTime().plusHours(12).toDate())
                .compact();

        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", token);
        hashMap.put("isNew", isNew);


        return hashMap;
    }


    public User queryUserByToken(String token) {
        try {
            User user = new User();
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            Long id = Long.valueOf(body.get("id").toString());
            user.setId(id);
            //先查缓存
            String redisKey = "TANHUA_USER_MOBILE_" + id;
            if (this.redisTemplate.hasKey(redisKey)) {
                String mobile = this.redisTemplate.opsForValue().get(redisKey);
                user.setMobile(mobile);
            } else {
                user = userMapper.selectById(id);
                //手机号放到redis，还得和token的过期时间保持一致
                String exp = body.get("exp").toString();//秒为单位
                Long timeout = Long.valueOf(exp) * 1000 - System.currentTimeMillis();
                this.redisTemplate.opsForValue().set(redisKey, user.getMobile(), timeout, TimeUnit.MILLISECONDS);
            }
            return user;
        } catch (Exception e) {
            log.error("解析用户出错", e);
            return null;
        }

    }
}